from pymysql import Connection,MySQLError

class DatabaseHandler:
    def __init__(self, host, port, user, password, autocommit=True):
        try:
            self.conn = Connection(
                host=host,
                port=port,
                user=user,
                password=password,
                autocommit=autocommit
            )
            self.cursor = self.conn.cursor()
        except MySQLError as e:
            print(f"数据库连接失败: {e}")
            self.conn = None
            self.cursor = None
    def create_database(self, db_name):
        if self.conn:
            try:
                self.cursor.execute(f'CREATE DATABASE IF NOT EXISTS {db_name}')
                print(f'数据库 {db_name} 创建成功或已存在')
            except MySQLError as e:
                print(f'创建数据库时出错: {e}')

    def close_connection(self):
        if self.cursor:
            self.cursor.close()
        if self.conn:
            self.conn.close()

            # 使用示例
if __name__ == "__main__":
    db_handler = DatabaseHandler(host='localhost', port=3306, user='root', password='123456')
    db_handler.create_database('test')
    db_handler.close_connection()